package cn.xbtop.blog.service.impl;

import cn.xbtop.blog.exception.BlogException;
import cn.xbtop.blog.mapper.AboutMapper;
import cn.xbtop.blog.pojo.About;
import cn.xbtop.blog.service.AboutService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mxb
 * @version 1.0
 * @date 2020/2/19 16:01
 */
@Service
public class AboutServiceImpl implements AboutService {

    @Resource
    private AboutMapper aboutMapper;

    /**
     * 通过id删除
     *
     * @param aboutId
     * @return
     */
    @Override
    public int deleteByPrimaryKey(Integer aboutId) {
        return aboutMapper.deleteByPrimaryKey(aboutId);
    }

    /**
     * 添加
     *
     * @param about
     * @return
     */
    @Override
    public int insert(About about) {
        return aboutMapper.insert(about);
    }

    /**
     * 查找所有
     *
     * @param aboutId
     * @return
     */
    @Override
    public About selectByPrimaryKey(Integer aboutId) {
        return aboutMapper.selectByPrimaryKey(aboutId);
    }

    /**
     * 更新
     *
     * @param about
     * @return
     */
    @Override
    public int updateByPrimaryKey(About about) {
        return aboutMapper.updateByPrimaryKey(about);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public About read() {
        About about = aboutMapper.getAbout();
        if (about == null) {
            return null;
        }
        //更新阅读数
        about.setAboutRead(about.getAboutRead() + 1);
        aboutMapper.updateByPrimaryKey(about);

        return about;
    }

    /**
     * 启用
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void enableById(Integer id) {
        //查询是否已经存在启用的关于我的
        About about = aboutMapper.getAbout();
        if (about != null) {
            throw new BlogException(1, "当前已存在关于我的");
        }
        about = aboutMapper.selectByPrimaryKey(id);
        about.setEnable(1);
        //aboutMapper.updateByPrimaryKey(about);

        aboutMapper.updateEnable(about);
    }

    /**
     * 弃用
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void disEnableById(Integer id) {
        //查询是否已经存在启用的关于我的
        //About about = aboutMapper.getAbout();
        //if(about==null){
        //    throw new BlogException(0,"请至少保留一篇启用中的关于我的");
        //}
        About about = aboutMapper.selectByPrimaryKey(id);
        about.setEnable(0);
        aboutMapper.updateEnable(about);
        //aboutMapper.updateByPrimaryKey(about);

    }

    @Override
    public List<About> list() {
        return aboutMapper.list();
    }
}
